<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Table Demo</title>
<style type="text/css">
.row {
    border-bottom: 1px red dotted;
    padding: 10px 0px;
}

.lspan {
    font-weight: bold;
    width: 150px;
    display: inline-block;
    margin-left: 10px;
}

#maskDiv {
    position: absolute;
    border: 0px green solid;
    width:100%;
    height: 100%;
    z-index: 30;
    background: rgb(0, 0, 0, 0.2);
    top:0px;
    left: 0px;
    display: none;
}

#maskDivLoading {
    position: absolute;
    border: 0px green solid;
    width:100%;
    height: 100%;
    z-index: 30;
    background: white;
    top:0px;
    left: 0px;
}

.img-stage{
    top: 50%;
    left: 50%;
    position: absolute;
    background:red;
}

#maskDivLoading img {
    top: 50%;
    left: 50%;
    height: 200px;
    width: 200px;
    margin-top : -120px;
    margin-left : -100px;
    position: absolute;
}

.buttonClass {
    border: 1px orange solid;
    background: white;
    color: orange;
    font-size: 16px;
    padding: 6px;
}

</style>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script src="js/jqueryui/jquery-ui.js"></script>
<link href="js/jqueryui/jquery-ui.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="js/datatables.css">
<script type="text/javascript" charset="utf8" src="js/datatables.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/fixedHeader.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="js/dataTables.fixedHeader.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/select.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="js/dataTables.select.min.js"></script>
<link rel="stylesheet" type="text/css" href="js/buttons.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="js/dataTables.buttons.min.js"></script>

<script type="text/javascript">
$(document).ready( function () {
	$( "#userUpdateDiv" ).dialog({
        autoOpen: false,
        width: 600,
        modal: true,
        title: 'User Operation',
        buttons: [
            {
                text: "Update",
                click: function() {
                	doUpdate();
                }
            },
            {
                text: "Delete",
                click: function() {
                	doDelete();
                }
            },
            {
            	id: "preBtn",
                text: "Previous",
                click: function() {
                    preHandler();
                }
            },
            {
            	id: 'nextBtn',
                text: "Next",
                click: function() {
                    nextHandler();
                }
            },
            {
                text: "Cancel",
                click: function() {
                    $( this ).dialog( "close" );
                }
            }
        ]
    });
	$('#maskDivLoading').show();
	
    mytable = $('#table_id').DataTable(
    		{
    			dom: 'Bfrtip', //'lfrtip',//'Blfrtip', //'Bflrtip',//
    			processing: false,
    		    searchDelay: 1000,
    			paging: true,
    			serverSide: true,
    			info: true,
    			fixedHeader: true,
    			lengthMenu: [
    				[5, 10, 25, 50, 75, 100 ],
    				['5 rows', '10 rows', '25 rows', '50 rows', '75 rows', '100 rows' ],
    				],
    			lengthChange : true,
    			 select: {
    		            style:    'os'
    		        },
   		        buttons: [
   		        	'pageLength',
   		        	{
   		                text: 'Select all',
   		                action: function () {
   		                    mytable.rows().select();
   		                }
   		            },
   		            {
   		                text: 'Select none',
   		                action: function () {
   		                    mytable.rows().deselect();
   		                }
   		            },
   		            {
   		                text: 'Get selected data',
   		                action: function () {
   		                    var count = mytable.rows( { selected: true } ).count();
   		 
   		                    
   		                }
   		            }
   		        ],
    			pageLength: 10,
    			//
    			fnRowCallback: function( nRow, aData, iDisplayIndex, iDisplayIndexFull ) {
    				if(aData.userStatus == '5') {
    					nRow.style = "font-size: 18px;font-weight: bold;color: orange;text-decoration:line-through";
    				}
    				
                },
    			rowCallback: function( row, data ) {
    			    
    			  },
    			order: [[5, 'desc']],
    			initComplete: function( settings, json ) {
    				$('#maskDivLoading').hide();
                },
    			fnDrawCallback : function(obj){
    	           //
    	        },
    			ajax: {
    			    url: "user/list",
    			    type: "GET",
    			    dataSrc: "data",
    			    data: {
    			    	
    			    }
    			  },
    			  columns: [
    				  {  //行号
   					    className: "td-no",
   					    orderable: false,
   					    searchable: false,
   					     data: null,
   					     render: function (data, type, row, meta) {
    					     var no = meta.settings._iDisplayStart + meta.row + 1;
    					     return no;
    					}
    				  },
    		            { 
    		              data: "loginName",
    		              searchable: true,
    		              orderable: true
    		            },
    		            { 
    		            	data: "userEmail",
    		            	searchable: true,
    	                    orderable: true
    		            },
    		            { 
    		            	data: "userPhone",
    		            	searchable: false,
                            orderable: false
    		            },
    		            { 
    		            	data: "userStatus",
    		            	searchable: false,
                            orderable: false,
                            render: function (data, type, row, meta) {
                            	
                                return row.userStatusDesc;
                           }
    		            },
    		            { 
    		            	data: "userCreateTime",
    		            	searchable: false,
                            orderable: true
    		            },
    		            { 
                            data: null,
                            searchable: false,
                            orderable: false,
                            
                        }
    		        ],
    		        columnDefs: [ {
   		                render:function(data,type,row, meta){
   		                   return "<input type='button' class='buttonClass' onclick='updateHandler(" + '"' + row.loginName + '"' + ");return false;' value='Operation'/>";
    		            },
    		            targets:6,
    		            createdCell: function (td, cellData, rowData, row, col) {
                          //console.log(td);
                          //$(td).css('background-color', 'green')
                        }
    		        }
    		        ]
    		}
    );
    
    mytable
    .on( 'select', function ( e, dt, type, indexes ) {
        var rowData = mytable.rows( indexes ).data().toArray();
        // get all select rows
        var count = mytable.rows( { selected: true } ).count();
        console.log(e);
    } )
    .on( 'deselect', function ( e, dt, type, indexes ) {
        //var rowData = mytable.rows( indexes ).data().toArray();
        //console.log(JSON.stringify( rowData ));
    } )
    .on( 'user-select', function ( e, dt, type, cell, originalEvent ) {
        if ( originalEvent.target.className === 'buttonClass' ) {
            e.preventDefault();
        }
    } );
});

function updateHandler(loginName) {
	$('#umsgs').html('');
	$('#loginName').val(loginName);
	/* $(".tabel").dataTable({aaData : d});//重新加载数据
	$(".table").dataTable().fnDeleteRow(index);//删除行
	$(".table").dataTable().fnUpdate("a", 1, 1, false);//修改行,最后一个参数，是否重绘表格
	$(".table").dataTable().fnUpdate(["a","b"],1);//修改列
	$(".table").DataTable().row.add(dc).draw();//添加行
	$(".table").dataTable().fnPageChange(page); //跳转到某页
	$(".table").dataTable().fnGetData();//得到页面中所有对象  
	$(".table").dataTable().fnSetColumnVis( 0, false);//隐藏列 
	table.draw(true);  // 重新绘制维护表格，分页将会被重置为第一页。

	table.draw( false );  //  重新绘制维护当前分页位置的表格。
	*/
	$( "#userUpdateDiv" ).dialog( "open" );
	
	var alldata = $('#table_id').dataTable().fnGetData();
	alldata.forEach(function(item, index) {
        if(item.loginName === loginName) {
            $('#email').val(item.userEmail);
            $('#phone').val(item.userPhone);
            $('#status').val(item.userStatus);
            $('#creationTime').val(item.userCreateTime);
            $('#indexHidden').val(index);
            var currentIndex = index;
            if(currentIndex == 0) {
                $("#preBtn" ).button( "disable" );
                $("#nextBtn" ).button( "enable" );
            } else {
                $("#nextBtn" ).button( "enable" );
                $("#preBtn" ).button( "enable" );
                var realTable = $('#table_id').dataTable();
                var allItems = realTable.fnGetData();
                if(currentIndex == allItems.length - 1) {
                    $("#nextBtn" ).button( "disable" );
                }
            }
            
            return;
        }
    });
	//$('#userUpdateDiv').show();
	//$('#maskDiv').show();
}

function nextHandler() {
    $('#umsgs').html('');
    var currentIndex = parseInt($('#indexHidden').val());
    var realTable = $('#table_id').dataTable();
    var allItems = realTable.fnGetData();
    currentIndex = currentIndex + 1;
    
    if(currentIndex >= allItems.length ) {
    	currentIndex = allItems.length - 1;
    	$("#nextBtn" ).button( "disable" );
    	$("#preBtn" ).button( "enable" );
    	//document.getElementById("nextBtn").disabled = true;
    	//document.getElementById("preBtn").disabled = false;
    } else {
    	$("#nextBtn" ).button( "enable" );
        $("#preBtn" ).button( "enable" );
    	//document.getElementById("preBtn").disabled = false;
    	//document.getElementById("nextBtn").disabled = false;
    }
    
    $('#indexHidden').val(currentIndex);
    
    var item = realTable.fnGetData(currentIndex);
    if(!item) {
    	return;
    }
    $('#loginName').val(item.loginName);
    $('#email').val(item.userEmail);
    $('#phone').val(item.userPhone);
    $('#status').val(item.userStatus);
    $('#creationTime').val(item.userCreateTime);
}

function preHandler() {
    $('#umsgs').html('');
    var currentIndex = parseInt($('#indexHidden').val());
    currentIndex = currentIndex - 1;
    if(currentIndex <= 0) {
    	currentIndex = 0;
    	$("#nextBtn" ).button( "enable" );
        $("#preBtn" ).button( "disable" );
    	//document.getElementById("preBtn").disabled = true;
    	//document.getElementById("nextBtn").disabled = false;
    } else {
    	$("#nextBtn" ).button( "enable" );
        $("#preBtn" ).button( "enable" );
    	//document.getElementById("nextBtn").disabled = false;
    	//document.getElementById("preBtn").disabled = false;
    }
    $('#indexHidden').val(currentIndex);
    var realTable = $('#table_id').dataTable();
    var item = realTable.fnGetData(currentIndex);
    if(!item) {
        return;
    }
    $('#loginName').val(item.loginName);
    $('#email').val(item.userEmail);
    $('#phone').val(item.userPhone);
    $('#status').val(item.userStatus);
    $('#creationTime').val(item.userCreateTime);
}

function doUpdate() {
    var index = $('#indexHidden').val();
    var email = $('#email').val();
    var phone = $('#phone').val();
    var status = $('#status').val();
    var creationTime = $('#creationTime').val();
    var loginName = $('#loginName').val();
    var userinfo = {
            "loginName" : loginName,
            "userEmail" : email,
            "userPhone" : phone,
            "userStatus" : status
    };
    
    var appJson = "application/json";
    $.ajax({
        url: '/user/update',
        type: 'POST',
        contentType: appJson,
        dataType: 'json',
        data: JSON.stringify(userinfo),
        beforeSend : function(req) {

        },
         success:function(data){
             var mymsg = data.data.msg || data.message;
             var dataCode = data.code;
             if(dataCode == '0') {
            	 $('#umsgs').html('<span style="color:green">'+ 'Update Successfully.'+ '</span>')
            	 var realTable = $('#table_id').dataTable();
            	var rowData = realTable.fnGetData(index);
            	rowData.userPhone = phone;
            	rowData.userEmail = email;
            	rowData.userStatus = status;
            	rowData.userCreateTime = creationTime;
            	realTable.fnDraw(false);
             } else {
            	 
            	 $('#umsgs').html('<span style="color:red">'+ 'Failed to update.' + '</span>')
             }
             
             
         },
         error:function(data){
                alert("Fail");
         }
    });
    
   
   
   
}

function doDelete() {
	var index = $('#indexHidden').val();
	var loginName = $('#loginName').val();
   var realTable = $('#table_id').dataTable();
   //realTable.fnDeleteRow(index);//删除行
   
   var appJson = "application/json";
   $.ajax({
       url: '/user/delete/' + loginName,
       type: 'DELETE',
       contentType: appJson,
       dataType: 'json',
       data: '',
       beforeSend : function(req) {

       },
        success:function(data){
            var mymsg = data.data.msg || data.message;
            var dataCode = data.code;
            if(dataCode == '0') {
                $('#umsgs').html('<span style="color:green">'+ 'Delete Successfully.'+ '</span>')
                var node = realTable.fnGetNodes(index);
                node.style = "font-size: 18px;font-weight: bold;color: orange;text-decoration:line-through";
                realTable.fnDraw(false);
                
            } else {
                
                $('#umsgs').html('<span style="color:red">'+ 'Failed to Delete.' + '</span>')
            }
            
            
        },
        error:function(data){
               alert("Fail");
        }
   });
   
   

}

function closeHandler() {
	$('#userUpdateDiv').hide();
	$('#maskDiv').hide();
	
}
</script>

</head>
<body>
<table id="table_id" class="display">
    <thead>
        <tr>
            <th>Id</th>
            <th>Login Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Status</th>
            <th>Creation Time</th>
            <th>Operation</th>
        </tr>
    </thead>
    <tbody>

    </tbody>
</table>
<!-- 
<div id="userUpdateDiv" style="background-color:#e3e3e3; position:absolute; z-index:31; top:50%;left:50%; width:500px; height:500px; margin-top:-250px; margin-left:-250px; border:2px solid green">
 -->

<div id="userUpdateDiv">
<div id="messages" class="msg">
    <div id="msgs" style="margin-left: 10px">
     
    </div>
    
</div>
<div id="row" class="row">
    <span id="lspan" class="lspan">
        Login Name: 
    </span>
    <span id="cspan">
        <input type="text" name="loginName" id="loginName" readonly="readonly"/>
    </span>
</div>

<div id="row2" class="row">
    <span id="lspan" class="lspan">
        Email: 
    </span>
    <span id="cspan">
        <input type="text" name="email" id="email"/>
    </span>
</div>

<div id="row3" class="row">
    <span id="lspan" class="lspan">
        Phone: 
    </span>
    <span id="cspan">
        <input type="text" name="phone" id="phone"/>
    </span>
</div>

<div id="row4" class="row">
    <span id="lspan" class="lspan">
        Status: 
    </span>
    <span id="cspan">
        <select name="status" id="status" >
            <option value="0">Invalid</option>
            <option value="1">Valid</option>
            <option value="2">Inactived</option>
            <option value="3">Locked</option>
            <option value="4">Not Login 3 Months</option>
            <option value="5">Logic Deleted</option>
        </select>
    </span>
</div>

<div id="row5" class="row">
    <span id="lspan" class="lspan">
        Creation Time: 
    </span>
    <span id="cspan">
        <input type="text" name="creationTime" id="creationTime"/>
    </span>
</div>

<div id="row6" class="row">
    <div id="umsgs">
    
    </div>
</div>
<input type="hidden" id="indexHidden"/>


</div>
<div id="maskDiv" >

</div>

<!-- <div id="maskDivLoading">
    <div class="img-stage">
        <img alt="" src="images/loading.gif">
    </div>
</div>
 -->
<div id="maskDivLoading">
        <img alt="" src="images/loading.gif">
</div>
</body>
</html>